package com.blacktech.dbu.core.config;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import org.springframework.lang.Nullable;

import java.io.IOException;
import java.util.Properties;

/**
 * YAML配置文件工厂类
 * 用于加载YAML格式的配置文件
 *
 * @author yanyunsong
 */
public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        Properties properties = factory.getObject();
        
        if (properties == null) {
            throw new IOException("Failed to load YAML configuration from " + resource.getResource().getFilename());
        }
        
        return new PropertiesPropertySource(name != null ? name : resource.getResource().getFilename(), properties);
    }
}